package org.mf.web.validation;

import org.mf.dao.UserDAO;
import org.mf.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Component(value = "userValidator")
public class UserValidator implements Validator {
	private UserDAO userDao;

	public boolean supports(Class<?> clazz) {
		return User.class.isAssignableFrom(clazz);
	}

	@Autowired
	public UserValidator(UserDAO userDao) {
		this.userDao = userDao;
	}

	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username",
				"required.username", "User name is required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "plainPassword",
				"required.plainPassword");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword",
				"required.confirmPassword");

		User user = (User) target;
		if (!user.getPlainPassword().equals(user.getConfirmPassword())) {
			errors.rejectValue("plainPassword", "notMatched.plainPassword");
		}

		if (!userDao.isUnique(user.getId(), "username", user.getUsername())) {
			errors.rejectValue("username", "notUnique.username",
					"Username has already been taken");
		}

		// input a general error message if any errors are preset
		if (errors.hasErrors()) {
			errors.reject("user.common", "User could not be saved");
		}
	}

}
